<template>
  <!-- <div class="shoplist">商品列表</div> -->
  <div class="box">
    <div class="box1">
      <div class="left">
        <ul >
          <li v-for="ele in arr" :key="ele.id" :class="{'curr':currId===ele.id}"
          @click="select(ele.id)">
            {{ele.name}}
          </li>
        </ul>
      </div>
    </div>
    <div class="box2">
      <div class="right">
        <router-view></router-view>
      </div>
    </div>

  </div>

</template>

<script>
export default {
  name: 'ShopList',
  methods: {
    select (id) {
      this.currId = id
      // 为了改变选择的样式
      this.$router.push({
        name: 'category',
        params: {
          id
        }
      })
    }
  },
  data () {
    return {
      arr: [],
      currId: null
    }
  },
  // 以下代码写在created中也能实现，但是现在这种方法的判断更加提前，性能更优化
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.$http.getHomeList()
        .then(res => {
          if (res.data.code === 200) {
            const hasId = vm.$route.params.id
            vm.arr = res.data.data.list.slice(1)
            // 因为路由中取出来的id是字符串，而上面的判断是全等，所以要先转为number
            vm.currId = hasId ? Number(to.params.id) : vm.arr[0].id
            // 以下代码最好写在nexttick函数中，此刻这样写主要为了测试不写能不能实现功能
            vm.$router.push({
              name: 'category',
              params: {
                id: vm.currId
              }
            })
          }
        })
    })
  }

}
</script>

<style scoped>

  .box{
    width: 100%!important;
    height: 100%!important;
  }
  .box1{
    width:30vw;
    height: 100%;
    box-sizing: border-box;
    background-color: #ccc;
    float: left;
     overflow-x:hidden;
  }
  .box2{
    width:70vw;
    height: 100%;
    background-color:#fff;
    float: left;
    overflow-x:hidden;
    box-sizing: border-box;

  }
  .left{
    height: 1000px;
  }
  .right{
    height: 2000px;
  }
  ul{
    margin-top:50px;
    text-align: center;
    font-weight: 600;
    width:100%;

  }
  li{
    height: 50px;
    line-height: 50px;
    width:100%;
  }

  .curr{
    background-color: red;
    color:#fff;
  }
</style>
